#include "pch.h"
#include "hci_state_machine.h"
#include "hci_comm.h"

struct state;
typedef void(*state_func_t)(struct state*);
uint16_t handle;

typedef struct state
{
	state_func_t next;

	// other stateful data

} state_t;

void do_state_initial(state_t*);
void do_state_reset(state_t*);
void do_state_connect(state_t*);
void do_state_listen(state_t*);
void do_state_final(state_t*);

uint8_t run_state_machine(void)
{
	state_t state = { do_state_initial };

	while (state.next) {
		state.next(&state);
	}

	return 0;
}


void do_state_initial(state_t* state)
{
	printf(_T("Enter State Initial\n"));
	if (blue_open() == 0)
	{
		state->next = do_state_reset;
	}
	else
	{
		// retry in 1s
		Sleep(1000);
	}
}

void do_state_reset(state_t* state)
{
	printf(_T("Enter State Reset\n"));
	if (blue_reset() == 0)
	{
		if (blue_scan_enable() == 0)
		{
			state->next = do_state_connect;
		}
	}
	else
	{
		// retry in 1s
		Sleep(1000);
	}
}

void do_state_connect(state_t* state)
{
	printf(_T("Enter State Connect\n"));
	uint8_t result;
	result = blue_connect(&handle);

	switch (result)
	{
	case 0:
		state->next = do_state_listen;
		break;
	case 1:
		state->next = do_state_reset;
		break;
	default:
		// stay in state
		break;
	}
}

void do_state_listen(state_t* state)
{
	printf(_T("Enter State Listen\n"));

	blue_setup_l2cap(0x40);
	blue_setup_l2cap(0x41);
	blue_sdp(handle);

	//blue_listen_hid();
	state->next = do_state_final;
}

void do_state_final(state_t* state)
{
	printf(_T("Enter State Final\n"));
	blue_close();
	state->next = 0;
}